package com.zxw.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zxw.common.core.base.enums.PasswordEncoderTypeEnum;
import com.zxw.auth.domain.entity.OauthClientDetails;
import com.zxw.auth.mapper.OauthClientDetailsMapper;
import com.zxw.auth.service.OauthClientDetailsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xuewei.Zhang
 * @since 2022-02-22
 */
@Service
@Slf4j
public class OauthClientDetailsServiceImpl extends ServiceImpl<OauthClientDetailsMapper, OauthClientDetails> implements OauthClientDetailsService, ClientDetailsService {

    @Resource
    private OauthClientDetailsService oauthClientDetailsService;

    @Override
    @Cacheable(cacheNames = "auth", key = "'oauth-client:'+#clientId")
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        OauthClientDetails oauthClientDetails = oauthClientDetailsService.getById(clientId);
        log.info(oauthClientDetails.toString());
        if (!ObjectUtil.hasEmpty(oauthClientDetails)) {
            BaseClientDetails clientDetails = new BaseClientDetails(
                    oauthClientDetails.getClientId(),
                    oauthClientDetails.getResourceIds(),
                    oauthClientDetails.getScope(),
                    oauthClientDetails.getAuthorizedGrantTypes(),
                    oauthClientDetails.getAuthorities(),
                    oauthClientDetails.getWebServerRedirectUri()
            );
            clientDetails.setClientSecret(PasswordEncoderTypeEnum.NOOP.getPrefix() + oauthClientDetails.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(oauthClientDetails.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(oauthClientDetails.getRefreshTokenValidity());
            return clientDetails;
        } else {
            log.info("client认证失败，{}", clientId);
            throw new NoSuchClientException("client_id不存在!");
        }
    }
}
